home *** CD-ROM | disk | FTP | other *** search
/ MacHack 2000 / MacHack 2000.toast / pc / The Hacks / MacHacksBug / Python 1.5.2c1 / Lib / rfc822.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2000-06-23  |  33.2 KB  |  1,002 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 1.5)
  3.  
  4. """RFC-822 message manipulation class.
  5.  
  6. XXX This is only a very rough sketch of a full RFC-822 parser;
  7. in particular the tokenizing of addresses does not adhere to all the
  8. quoting rules.
  9.  
  10. Directions for use:
  11.  
  12. To create a Message object: first open a file, e.g.:
  13.   fp = open(file, 'r')
  14. You can use any other legal way of getting an open file object, e.g. use
  15. sys.stdin or call os.popen().
  16. Then pass the open file object to the Message() constructor:
  17.   m = Message(fp)
  18.  
  19. This class can work with any input object that supports a readline
  20. method.  If the input object has seek and tell capability, the
  21. rewindbody method will work; also illegal lines will be pushed back
  22. onto the input stream.  If the input object lacks seek but has an
  23. `unread' method that can push back a line of input, Message will use
  24. that to push back illegal lines.  Thus this class can be used to parse
  25. messages coming from a buffered stream.
  26.  
  27. The optional `seekable' argument is provided as a workaround for
  28. certain stdio libraries in which tell() discards buffered data before
  29. discovering that the lseek() system call doesn't work.  For maximum
  30. portability, you should set the seekable argument to zero to prevent
  31. that initial \\code{tell} when passing in an unseekable object such as
  32. a a file object created from a socket object.  If it is 1 on entry --
  33. which it is by default -- the tell() method of the open file object is
  34. called once; if this raises an exception, seekable is reset to 0.  For 
  35. other nonzero values of seekable, this test is not made.
  36.  
  37. To get the text of a particular header there are several methods:
  38.   str = m.getheader(name)
  39.   str = m.getrawheader(name)
  40. where name is the name of the header, e.g. 'Subject'.
  41. The difference is that getheader() strips the leading and trailing
  42. whitespace, while getrawheader() doesn't.  Both functions retain
  43. embedded whitespace (including newlines) exactly as they are
  44. specified in the header, and leave the case of the text unchanged.
  45.  
  46. For addresses and address lists there are functions
  47.   realname, mailaddress = m.getaddr(name) and
  48.   list = m.getaddrlist(name)
  49. where the latter returns a list of (realname, mailaddr) tuples.
  50.  
  51. There is also a method
  52.   time = m.getdate(name)
  53. which parses a Date-like field and returns a time-compatible tuple,
  54. i.e. a tuple such as returned by time.localtime() or accepted by
  55. time.mktime().
  56.  
  57. See the class definition for lower level access methods.
  58.  
  59. There are also some utility functions here.
  60. """
  61. import string
  62. import time
  63. _blanklines = ('\r\n', '\n')
  64.  
  65. class Message:
  66.     '''Represents a single RFC-822-compliant message.'''
  67.     
  68.     def __init__(self, fp, seekable = 1):
  69.         '''Initialize the class instance and read the headers.'''
  70.         if seekable == 1:
  71.             
  72.             try:
  73.                 fp.tell()
  74.             except:
  75.                 seekable = 0
  76.  
  77.             seekable = 1
  78.         
  79.         self.fp = fp
  80.         self.seekable = seekable
  81.         self.startofheaders = None
  82.         self.startofbody = None
  83.         if self.seekable:
  84.             
  85.             try:
  86.                 self.startofheaders = self.fp.tell()
  87.             except IOError:
  88.                 self.seekable = 0
  89.  
  90.         
  91.         self.readheaders()
  92.         if self.seekable:
  93.             
  94.             try:
  95.                 self.startofbody = self.fp.tell()
  96.             except IOError:
  97.                 self.seekable = 0
  98.  
  99.         
  100.  
  101.     
  102.     def rewindbody(self):
  103.         '''Rewind the file to the start of the body (if seekable).'''
  104.         if not (self.seekable):
  105.             raise IOError, 'unseekable file'
  106.         
  107.         self.fp.seek(self.startofbody)
  108.  
  109.     
  110.     def readheaders(self):
  111.         '''Read header lines.
  112.         
  113.         Read header lines up to the entirely blank line that
  114.         terminates them.  The (normally blank) line that ends the
  115.         headers is skipped, but not included in the returned list.
  116.         If a non-header line ends the headers, (which is an error),
  117.         an attempt is made to backspace over it; it is never
  118.         included in the returned list.
  119.         
  120.         The variable self.status is set to the empty string if all
  121.         went well, otherwise it is an error message.
  122.         The variable self.headers is a completely uninterpreted list
  123.         of lines contained in the header (so printing them will
  124.         reproduce the header exactly as it appears in the file).
  125.         '''
  126.         self.dict = { }
  127.         self.unixfrom = ''
  128.         self.headers = list = []
  129.         self.status = ''
  130.         headerseen = ''
  131.         firstline = 1
  132.         startofline = unread = tell = None
  133.         if hasattr(self.fp, 'unread'):
  134.             unread = self.fp.unread
  135.         elif self.seekable:
  136.             tell = self.fp.tell
  137.         
  138.         while 1:
  139.             if tell:
  140.                 startofline = tell()
  141.             
  142.             line = self.fp.readline()
  143.             if not line:
  144.                 self.status = 'EOF in headers'
  145.                 break
  146.             
  147.             if firstline and line[:5] == 'From ':
  148.                 self.unixfrom = self.unixfrom + line
  149.                 continue
  150.             
  151.             firstline = 0
  152.             if headerseen and line[0] in ' \t':
  153.                 list.append(line)
  154.                 x = self.dict[headerseen] + '\n ' + string.strip(line)
  155.                 self.dict[headerseen] = string.strip(x)
  156.                 continue
  157.             elif self.iscomment(line):
  158.                 continue
  159.             elif self.islast(line):
  160.                 break
  161.             
  162.             headerseen = self.isheader(line)
  163.             if headerseen:
  164.                 list.append(line)
  165.                 self.dict[headerseen] = string.strip(line[len(headerseen) + 2:])
  166.                 continue
  167.             elif not (self.dict):
  168.                 self.status = 'No headers'
  169.             else:
  170.                 self.status = 'Non-header line where header expected'
  171.             if unread:
  172.                 unread(line)
  173.             elif tell:
  174.                 self.fp.seek(startofline)
  175.             else:
  176.                 self.status = self.status + '; bad seek'
  177.             break
  178.  
  179.     
  180.     def isheader(self, line):
  181.         '''Determine whether a given line is a legal header.
  182.  
  183.         This method should return the header name, suitably canonicalized.
  184.         You may override this method in order to use Message parsing
  185.         on tagged data in RFC822-like formats with special header formats.
  186.         '''
  187.         i = string.find(line, ':')
  188.         if i > 0:
  189.             return string.lower(line[:i])
  190.         else:
  191.             return None
  192.  
  193.     
  194.     def islast(self, line):
  195.         """Determine whether a line is a legal end of RFC-822 headers.
  196.         
  197.         You may override this method if your application wants
  198.         to bend the rules, e.g. to strip trailing whitespace,
  199.         or to recognise MH template separators ('--------').
  200.         For convenience (e.g. for code reading from sockets) a
  201.         line consisting of \r
  202.  also matches.                
  203.         """
  204.         return line in _blanklines
  205.  
  206.     
  207.     def iscomment(self, line):
  208.         '''Determine whether a line should be skipped entirely.
  209.  
  210.         You may override this method in order to use Message parsing
  211.         on tagged data in RFC822-like formats that support embedded
  212.         comments or free-text data.
  213.         '''
  214.         return None
  215.  
  216.     
  217.     def getallmatchingheaders(self, name):
  218.         '''Find all header lines matching a given header name.
  219.         
  220.         Look through the list of headers and find all lines
  221.         matching a given header name (and their continuation
  222.         lines).  A list of the lines is returned, without
  223.         interpretation.  If the header does not occur, an
  224.         empty list is returned.  If the header occurs multiple
  225.         times, all occurrences are returned.  Case is not
  226.         important in the header name.
  227.         '''
  228.         name = string.lower(name) + ':'
  229.         n = len(name)
  230.         list = []
  231.         hit = 0
  232.         for line in self.headers:
  233.             if string.lower(line[:n]) == name:
  234.                 hit = 1
  235.             elif line[:1] not in string.whitespace:
  236.                 hit = 0
  237.             
  238.             if hit:
  239.                 list.append(line)
  240.             
  241.         
  242.         return list
  243.  
  244.     
  245.     def getfirstmatchingheader(self, name):
  246.         '''Get the first header line matching name.
  247.         
  248.         This is similar to getallmatchingheaders, but it returns
  249.         only the first matching header (and its continuation
  250.         lines).
  251.         '''
  252.         name = string.lower(name) + ':'
  253.         n = len(name)
  254.         list = []
  255.         hit = 0
  256.         for line in self.headers:
  257.             if hit:
  258.                 if line[:1] not in string.whitespace:
  259.                     break
  260.                 
  261.             elif string.lower(line[:n]) == name:
  262.                 hit = 1
  263.             
  264.         
  265.         return list
  266.  
  267.     
  268.     def getrawheader(self, name):
  269.         '''A higher-level interface to getfirstmatchingheader().
  270.         
  271.         Return a string containing the literal text of the
  272.         header but with the keyword stripped.  All leading,
  273.         trailing and embedded whitespace is kept in the
  274.         string, however.
  275.         Return None if the header does not occur.
  276.         '''
  277.         list = self.getfirstmatchingheader(name)
  278.         if not list:
  279.             return None
  280.         
  281.         list[0] = list[0][len(name) + 1:]
  282.         return string.joinfields(list, '')
  283.  
  284.     
  285.     def getheader(self, name, default = None):
  286.         """Get the header value for a name.
  287.         
  288.         This is the normal interface: it return a stripped
  289.         version of the header value for a given header name,
  290.         or None if it doesn't exist.  This uses the dictionary
  291.         version which finds the *last* such header.
  292.         """
  293.         
  294.         try:
  295.             return self.dict[string.lower(name)]
  296.         except KeyError:
  297.             return default
  298.  
  299.  
  300.     get = getheader
  301.     
  302.     def getaddr(self, name):
  303.         """Get a single address from a header, as a tuple.
  304.         
  305.         An example return value:
  306.         ('Guido van Rossum', 'guido@cwi.nl')
  307.         """
  308.         alist = self.getaddrlist(name)
  309.         if alist:
  310.             return alist[0]
  311.         else:
  312.             return (None, None)
  313.  
  314.     
  315.     def getaddrlist(self, name):
  316.         '''Get a list of addresses from a header.
  317.  
  318.         Retrieves a list of addresses from a header, where each address is a
  319.         tuple as returned by getaddr().  Scans all named headers, so it works
  320.         properly with multiple To: or Cc: headers for example.
  321.  
  322.         '''
  323.         raw = []
  324.         for h in self.getallmatchingheaders(name):
  325.             if h[0] in ' \t':
  326.                 raw.append(h)
  327.             elif raw:
  328.                 raw.append(', ')
  329.             
  330.             i = string.find(h, ':')
  331.             if i > 0:
  332.                 addr = h[i + 1:]
  333.             
  334.             raw.append(addr)
  335.         
  336.         alladdrs = string.join(raw, '')
  337.         a = AddrlistClass(alladdrs)
  338.         return a.getaddrlist()
  339.  
  340.     
  341.     def getdate(self, name):
  342.         '''Retrieve a date field from a header.
  343.         
  344.         Retrieves a date field from the named header, returning
  345.         a tuple compatible with time.mktime().
  346.         '''
  347.         
  348.         try:
  349.             data = self[name]
  350.         except KeyError:
  351.             return None
  352.  
  353.         return parsedate(data)
  354.  
  355.     
  356.     def getdate_tz(self, name):
  357.         """Retrieve a date field from a header as a 10-tuple.
  358.         
  359.         The first 9 elements make up a tuple compatible with
  360.         time.mktime(), and the 10th is the offset of the poster's
  361.         time zone from GMT/UTC.
  362.         """
  363.         
  364.         try:
  365.             data = self[name]
  366.         except KeyError:
  367.             return None
  368.  
  369.         return parsedate_tz(data)
  370.  
  371.     
  372.     def __len__(self):
  373.         '''Get the number of headers in a message.'''
  374.         return len(self.dict)
  375.  
  376.     
  377.     def __getitem__(self, name):
  378.         '''Get a specific header, as from a dictionary.'''
  379.         return self.dict[string.lower(name)]
  380.  
  381.     
  382.     def __setitem__(self, name, value):
  383.         '''Set the value of a header.
  384.  
  385.         Note: This is not a perfect inversion of __getitem__, because 
  386.         any changed headers get stuck at the end of the raw-headers list
  387.         rather than where the altered header was.
  388.         '''
  389.         del self[name]
  390.         self.dict[string.lower(name)] = value
  391.         text = name + ': ' + value
  392.         lines = string.split(text, '\n')
  393.         for line in lines:
  394.             self.headers.append(line + '\n')
  395.         
  396.  
  397.     
  398.     def __delitem__(self, name):
  399.         '''Delete all occurrences of a specific header, if it is present.'''
  400.         name = string.lower(name)
  401.         if not self.dict.has_key(name):
  402.             return None
  403.         
  404.         del self.dict[name]
  405.         name = name + ':'
  406.         n = len(name)
  407.         list = []
  408.         hit = 0
  409.         for i in range(len(self.headers)):
  410.             line = self.headers[i]
  411.             if string.lower(line[:n]) == name:
  412.                 hit = 1
  413.             elif line[:1] not in string.whitespace:
  414.                 hit = 0
  415.             
  416.             if hit:
  417.                 list.append(i)
  418.             
  419.         
  420.         list.reverse()
  421.         for i in list:
  422.             del self.headers[i]
  423.         
  424.  
  425.     
  426.     def has_key(self, name):
  427.         '''Determine whether a message contains the named header.'''
  428.         return self.dict.has_key(string.lower(name))
  429.  
  430.     
  431.     def keys(self):
  432.         """Get all of a message's header field names."""
  433.         return self.dict.keys()
  434.  
  435.     
  436.     def values(self):
  437.         """Get all of a message's header field values."""
  438.         return self.dict.values()
  439.  
  440.     
  441.     def items(self):
  442.         """Get all of a message's headers.
  443.         
  444.         Returns a list of name, value tuples.
  445.         """
  446.         return self.dict.items()
  447.  
  448.     
  449.     def __str__(self):
  450.         str = ''
  451.         for hdr in self.headers:
  452.             str = str + hdr
  453.         
  454.         return str
  455.  
  456.  
  457.  
  458. def unquote(str):
  459.     '''Remove quotes from a string.'''
  460.     if len(str) > 1:
  461.         if str[0] == '"' and str[-1:] == '"':
  462.             return str[1:-1]
  463.         
  464.         if str[0] == '<' and str[-1:] == '>':
  465.             return str[1:-1]
  466.         
  467.     
  468.     return str
  469.  
  470.  
  471. def quote(str):
  472.     '''Add quotes around a string.'''
  473.     return '"%s"' % string.join(string.split(string.join(string.split(str, '\\'), '\\\\'), '"'), '\\"')
  474.  
  475.  
  476. def parseaddr(address):
  477.     '''Parse an address into a (realname, mailaddr) tuple.'''
  478.     a = AddrlistClass(address)
  479.     list = a.getaddrlist()
  480.     if not list:
  481.         return (None, None)
  482.     else:
  483.         return list[0]
  484.  
  485.  
  486. class AddrlistClass:
  487.     '''Address parser class by Ben Escoto.
  488.     
  489.     To understand what this class does, it helps to have a copy of
  490.     RFC-822 in front of you.
  491.  
  492.     Note: this class interface is deprecated and may be removed in the future.
  493.     Use rfc822.AddressList instead.
  494.     '''
  495.     
  496.     def __init__(self, field):
  497.         """Initialize a new instance.
  498.         
  499.         `field' is an unparsed address header field, containing
  500.         one or more addresses.
  501.         """
  502.         self.specials = '()<>@,:;."[]'
  503.         self.pos = 0
  504.         self.LWS = ' \t'
  505.         self.CR = '\r\n'
  506.         self.atomends = self.specials + self.LWS + self.CR
  507.         self.field = field
  508.         self.commentlist = []
  509.  
  510.     
  511.     def gotonext(self):
  512.         '''Parse up to the start of the next address.'''
  513.         while self.pos < len(self.field):
  514.             if self.field[self.pos] in self.LWS + '\n\r':
  515.                 self.pos = self.pos + 1
  516.             elif self.field[self.pos] == '(':
  517.                 self.commentlist.append(self.getcomment())
  518.             else:
  519.                 break
  520.  
  521.     
  522.     def getaddrlist(self):
  523.         '''Parse all addresses.
  524.         
  525.         Returns a list containing all of the addresses.
  526.         '''
  527.         ad = self.getaddress()
  528.         if ad:
  529.             return ad + self.getaddrlist()
  530.         else:
  531.             return []
  532.  
  533.     
  534.     def getaddress(self):
  535.         '''Parse the next address.'''
  536.         self.commentlist = []
  537.         self.gotonext()
  538.         oldpos = self.pos
  539.         oldcl = self.commentlist
  540.         plist = self.getphraselist()
  541.         self.gotonext()
  542.         returnlist = []
  543.         if self.pos >= len(self.field):
  544.             if plist:
  545.                 returnlist = [
  546.                     (string.join(self.commentlist), plist[0])]
  547.             
  548.         elif self.field[self.pos] in '.@':
  549.             self.pos = oldpos
  550.             self.commentlist = oldcl
  551.             addrspec = self.getaddrspec()
  552.             returnlist = [
  553.                 (string.join(self.commentlist), addrspec)]
  554.         elif self.field[self.pos] == ':':
  555.             returnlist = []
  556.             self.pos = self.pos + 1
  557.             while self.pos < len(self.field):
  558.                 self.gotonext()
  559.                 if self.field[self.pos] == ';':
  560.                     self.pos = self.pos + 1
  561.                     break
  562.                 
  563.                 returnlist = returnlist + self.getaddress()
  564.         elif self.field[self.pos] == '<':
  565.             routeaddr = self.getrouteaddr()
  566.             if self.commentlist:
  567.                 returnlist = [
  568.                     (string.join(plist) + ' (' + string.join(self.commentlist) + ')', routeaddr)]
  569.             else:
  570.                 returnlist = [
  571.                     (string.join(plist), routeaddr)]
  572.         elif plist:
  573.             returnlist = [
  574.                 (string.join(self.commentlist), plist[0])]
  575.         elif self.field[self.pos] in self.specials:
  576.             self.pos = self.pos + 1
  577.         
  578.         self.gotonext()
  579.         if self.pos < len(self.field) and self.field[self.pos] == ',':
  580.             self.pos = self.pos + 1
  581.         
  582.         return returnlist
  583.  
  584.     
  585.     def getrouteaddr(self):
  586.         '''Parse a route address (Return-path value).
  587.         
  588.         This method just skips all the route stuff and returns the addrspec.
  589.         '''
  590.         if self.field[self.pos] != '<':
  591.             return None
  592.         
  593.         expectroute = 0
  594.         self.pos = self.pos + 1
  595.         self.gotonext()
  596.         adlist = None
  597.         while self.pos < len(self.field):
  598.             if expectroute:
  599.                 self.getdomain()
  600.                 expectroute = 0
  601.             elif self.field[self.pos] == '>':
  602.                 self.pos = self.pos + 1
  603.                 break
  604.             elif self.field[self.pos] == '@':
  605.                 self.pos = self.pos + 1
  606.                 expectroute = 1
  607.             elif self.field[self.pos] == ':':
  608.                 self.pos = self.pos + 1
  609.                 expectaddrspec = 1
  610.             else:
  611.                 adlist = self.getaddrspec()
  612.                 self.pos = self.pos + 1
  613.                 break
  614.             self.gotonext()
  615.         return adlist
  616.  
  617.     
  618.     def getaddrspec(self):
  619.         '''Parse an RFC-822 addr-spec.'''
  620.         aslist = []
  621.         self.gotonext()
  622.         while self.pos < len(self.field):
  623.             if self.field[self.pos] == '.':
  624.                 aslist.append('.')
  625.                 self.pos = self.pos + 1
  626.             elif self.field[self.pos] == '"':
  627.                 aslist.append(self.getquote())
  628.             elif self.field[self.pos] in self.atomends:
  629.                 break
  630.             else:
  631.                 aslist.append(self.getatom())
  632.             self.gotonext()
  633.         if self.pos >= len(self.field) or self.field[self.pos] != '@':
  634.             return string.join(aslist, '')
  635.         
  636.         aslist.append('@')
  637.         self.pos = self.pos + 1
  638.         self.gotonext()
  639.         return string.join(aslist, '') + self.getdomain()
  640.  
  641.     
  642.     def getdomain(self):
  643.         '''Get the complete domain name from an address.'''
  644.         sdlist = []
  645.         while self.pos < len(self.field):
  646.             if self.field[self.pos] in self.LWS:
  647.                 self.pos = self.pos + 1
  648.             elif self.field[self.pos] == '(':
  649.                 self.commentlist.append(self.getcomment())
  650.             elif self.field[self.pos] == '[':
  651.                 sdlist.append(self.getdomainliteral())
  652.             elif self.field[self.pos] == '.':
  653.                 self.pos = self.pos + 1
  654.                 sdlist.append('.')
  655.             elif self.field[self.pos] in self.atomends:
  656.                 break
  657.             else:
  658.                 sdlist.append(self.getatom())
  659.         return string.join(sdlist, '')
  660.  
  661.     
  662.     def getdelimited(self, beginchar, endchars, allowcomments = 1):
  663.         """Parse a header fragment delimited by special characters.
  664.         
  665.         `beginchar' is the start character for the fragment.
  666.         If self is not looking at an instance of `beginchar' then
  667.         getdelimited returns the empty string.
  668.         
  669.         `endchars' is a sequence of allowable end-delimiting characters.
  670.         Parsing stops when one of these is encountered.
  671.         
  672.         If `allowcomments' is non-zero, embedded RFC-822 comments
  673.         are allowed within the parsed fragment.
  674.         """
  675.         if self.field[self.pos] != beginchar:
  676.             return ''
  677.         
  678.         slist = [
  679.             '']
  680.         quote = 0
  681.         self.pos = self.pos + 1
  682.         while self.pos < len(self.field):
  683.             if quote == 1:
  684.                 slist.append(self.field[self.pos])
  685.                 quote = 0
  686.             elif self.field[self.pos] in endchars:
  687.                 self.pos = self.pos + 1
  688.                 break
  689.             elif allowcomments and self.field[self.pos] == '(':
  690.                 slist.append(self.getcomment())
  691.             elif self.field[self.pos] == '\\':
  692.                 quote = 1
  693.             else:
  694.                 slist.append(self.field[self.pos])
  695.             self.pos = self.pos + 1
  696.         return string.join(slist, '')
  697.  
  698.     
  699.     def getquote(self):
  700.         """Get a quote-delimited fragment from self's field."""
  701.         return self.getdelimited('"', '"\r', 0)
  702.  
  703.     
  704.     def getcomment(self):
  705.         """Get a parenthesis-delimited fragment from self's field."""
  706.         return self.getdelimited('(', ')\r', 1)
  707.  
  708.     
  709.     def getdomainliteral(self):
  710.         '''Parse an RFC-822 domain-literal.'''
  711.         return self.getdelimited('[', ']\r', 0)
  712.  
  713.     
  714.     def getatom(self):
  715.         '''Parse an RFC-822 atom.'''
  716.         atomlist = [
  717.             '']
  718.         while self.pos < len(self.field):
  719.             if self.field[self.pos] in self.atomends:
  720.                 break
  721.             else:
  722.                 atomlist.append(self.field[self.pos])
  723.             self.pos = self.pos + 1
  724.         return string.join(atomlist, '')
  725.  
  726.     
  727.     def getphraselist(self):
  728.         '''Parse a sequence of RFC-822 phrases.
  729.         
  730.         A phrase is a sequence of words, which are in turn either
  731.         RFC-822 atoms or quoted-strings.  Phrases are canonicalized
  732.         by squeezing all runs of continuous whitespace into one space.
  733.         '''
  734.         plist = []
  735.         while self.pos < len(self.field):
  736.             if self.field[self.pos] in self.LWS:
  737.                 self.pos = self.pos + 1
  738.             elif self.field[self.pos] == '"':
  739.                 plist.append(self.getquote())
  740.             elif self.field[self.pos] == '(':
  741.                 self.commentlist.append(self.getcomment())
  742.             elif self.field[self.pos] in self.atomends:
  743.                 break
  744.             else:
  745.                 plist.append(self.getatom())
  746.         return plist
  747.  
  748.  
  749.  
  750. class AddressList(AddrlistClass):
  751.     '''An AddressList encapsulates a list of parsed RFC822 addresses.'''
  752.     
  753.     def __init__(self, field):
  754.         AddrlistClass.__init__(self, field)
  755.         if field:
  756.             self.addresslist = self.getaddrlist()
  757.         else:
  758.             self.addresslist = []
  759.  
  760.     
  761.     def __len__(self):
  762.         return len(self.addresslist)
  763.  
  764.     
  765.     def __str__(self):
  766.         return string.joinfields(map(dump_address_pair, self.addresslist), ', ')
  767.  
  768.     
  769.     def __add__(self, other):
  770.         newaddr = AddressList(None)
  771.         newaddr.addresslist = self.addresslist[:]
  772.         for x in other.addresslist:
  773.             pass
  774.         
  775.         return newaddr
  776.  
  777.     
  778.     def __sub__(self, other):
  779.         newaddr = AddressList(None)
  780.         for x in self.addresslist:
  781.             pass
  782.         
  783.         return newaddr
  784.  
  785.     
  786.     def __getitem__(self, index):
  787.         return self.addrlist[index]
  788.  
  789.  
  790.  
  791. def dump_address_pair(pair):
  792.     '''Dump a (name, address) pair in a canonicalized form.'''
  793.     if pair[0]:
  794.         return '"' + pair[0] + '" <' + pair[1] + '>'
  795.     else:
  796.         return pair[1]
  797.  
  798. _monthnames = [
  799.     'jan',
  800.     'feb',
  801.     'mar',
  802.     'apr',
  803.     'may',
  804.     'jun',
  805.     'jul',
  806.     'aug',
  807.     'sep',
  808.     'oct',
  809.     'nov',
  810.     'dec',
  811.     'january',
  812.     'february',
  813.     'march',
  814.     'april',
  815.     'may',
  816.     'june',
  817.     'july',
  818.     'august',
  819.     'september',
  820.     'october',
  821.     'november',
  822.     'december']
  823. _daynames = [
  824.     'mon',
  825.     'tue',
  826.     'wed',
  827.     'thu',
  828.     'fri',
  829.     'sat',
  830.     'sun']
  831. _timezones = {
  832.     'UT': 0,
  833.     'UTC': 0,
  834.     'GMT': 0,
  835.     'Z': 0,
  836.     'AST': -400,
  837.     'ADT': -300,
  838.     'EST': -500,
  839.     'EDT': -400,
  840.     'CST': -600,
  841.     'CDT': -500,
  842.     'MST': -700,
  843.     'MDT': -600,
  844.     'PST': -800,
  845.     'PDT': -700 }
  846.  
  847. def parsedate_tz(data):
  848.     '''Convert a date string to a time tuple.
  849.     
  850.     Accounts for military timezones.
  851.     '''
  852.     data = string.split(data)
  853.     if data[0][-1] in (',', '.') or string.lower(data[0]) in _daynames:
  854.         del data[0]
  855.     
  856.     if len(data) == 3:
  857.         stuff = string.split(data[0], '-')
  858.         if len(stuff) == 3:
  859.             data = stuff + data[1:]
  860.         
  861.     
  862.     if len(data) == 4:
  863.         s = data[3]
  864.         i = string.find(s, '+')
  865.         if i > 0:
  866.             data[3:] = [
  867.                 s[:i],
  868.                 s[i + 1:]]
  869.         else:
  870.             data.append('')
  871.     
  872.     if len(data) < 5:
  873.         return None
  874.     
  875.     data = data[:5]
  876.     (dd, mm, yy, tm, tz) = data
  877.     mm = string.lower(mm)
  878.     if not (mm in _monthnames):
  879.         (dd, mm) = (mm, string.lower(dd))
  880.         if not (mm in _monthnames):
  881.             return None
  882.         
  883.     
  884.     mm = _monthnames.index(mm) + 1
  885.     if dd[-1] == ',':
  886.         dd = dd[:-1]
  887.     
  888.     i = string.find(yy, ':')
  889.     if i > 0:
  890.         (yy, tm) = (tm, yy)
  891.     
  892.     if yy[-1] == ',':
  893.         yy = yy[:-1]
  894.     
  895.     if yy[0] not in string.digits:
  896.         (yy, tz) = (tz, yy)
  897.     
  898.     if tm[-1] == ',':
  899.         tm = tm[:-1]
  900.     
  901.     tm = string.splitfields(tm, ':')
  902.     if len(tm) == 2:
  903.         (thh, tmm) = tm
  904.         tss = '0'
  905.     elif len(tm) == 3:
  906.         (thh, tmm, tss) = tm
  907.     else:
  908.         return None
  909.     
  910.     try:
  911.         yy = string.atoi(yy)
  912.         dd = string.atoi(dd)
  913.         thh = string.atoi(thh)
  914.         tmm = string.atoi(tmm)
  915.         tss = string.atoi(tss)
  916.     except string.atoi_error:
  917.         return None
  918.  
  919.     tzoffset = None
  920.     tz = string.upper(tz)
  921.     if _timezones.has_key(tz):
  922.         tzoffset = _timezones[tz]
  923.     else:
  924.         
  925.         try:
  926.             tzoffset = string.atoi(tz)
  927.         except string.atoi_error:
  928.             pass
  929.  
  930.     if tzoffset:
  931.         if tzoffset < 0:
  932.             tzsign = -1
  933.             tzoffset = -tzoffset
  934.         else:
  935.             tzsign = 1
  936.         tzoffset = tzsign * ((tzoffset / 100) * 3600 + (tzoffset % 100) * 60)
  937.     
  938.     tuple = (yy, mm, dd, thh, tmm, tss, 0, 0, 0, tzoffset)
  939.     return tuple
  940.  
  941.  
  942. def parsedate(data):
  943.     '''Convert a time string to a time tuple.'''
  944.     t = parsedate_tz(data)
  945.     if type(t) == type(()):
  946.         return t[:9]
  947.     else:
  948.         return t
  949.  
  950.  
  951. def mktime_tz(data):
  952.     '''Turn a 10-tuple as returned by parsedate_tz() into a UTC timestamp.'''
  953.     if data[9] is None:
  954.         return time.mktime(data[:8] + (-1,))
  955.     else:
  956.         t = time.mktime(data[:8] + (0,))
  957.         return t - data[9] - time.timezone
  958.  
  959. if __name__ == '__main__':
  960.     import sys
  961.     import os
  962.     file = os.path.join(os.environ['HOME'], 'Mail/inbox/1')
  963.     if sys.argv[1:]:
  964.         file = sys.argv[1]
  965.     
  966.     f = open(file, 'r')
  967.     m = Message(f)
  968.     print 'From:', m.getaddr('from')
  969.     print 'To:', m.getaddrlist('to')
  970.     print 'Subject:', m.getheader('subject')
  971.     print 'Date:', m.getheader('date')
  972.     date = m.getdate_tz('date')
  973.     if date:
  974.         print 'ParsedDate:', time.asctime(date[:-1]),
  975.         hhmmss = date[-1]
  976.         (hhmm, ss) = divmod(hhmmss, 60)
  977.         (hh, mm) = divmod(hhmm, 60)
  978.         print '%+03d%02d' % (hh, mm),
  979.         if ss:
  980.             print '.%02d' % ss,
  981.         
  982.         print 
  983.     else:
  984.         print 'ParsedDate:', None
  985.     m.rewindbody()
  986.     n = 0
  987.     while f.readline():
  988.         n = n + 1
  989.     print 'Lines:', n
  990.     print '-' * 70
  991.     print 'len =', len(m)
  992.     if m.has_key('Date'):
  993.         print 'Date =', m['Date']
  994.     
  995.     if m.has_key('X-Nonsense'):
  996.         pass
  997.     
  998.     print 'keys =', m.keys()
  999.     print 'values =', m.values()
  1000.     print 'items =', m.items()
  1001.  
  1002.